//单调递增的数字
class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string str = to_string(n);
        //找到第一个非递增
        bool is = false;
        for(size_t i = 0; i < str.size() - 1 ; ++i)
        {
            if(is) 
            {
                str[i] = '9';
                continue;
            }
            int dst = i;
            if(str[i] > str[i+1])
            {
                while(dst > 0 && str[dst] == str[dst-1])
                {
                    str[dst] = '9';
                    --dst;
                }
                str[dst]--;
                is = true;
            }
        }
        if(is) str[str.size()-1] = '9';
        return stoi(str);
    }
};

//坏了的计算器
class Solution {
public:
    int brokenCalc(int startValue, int target) {
        //正难则反
        int count = 0;
        while(true)
        {
            if(target == startValue) return count;
            else if(target < startValue)
            {
                target++;
            }
            else
            {
                if(target % 2 == 0) target /= 2;
                else target++;
            }
            count++;
        }
        return count;
    }
};

//合并区间
class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int n = intervals.size();
        sort(intervals.begin(),intervals.end());
        int &left = intervals[0][0] , right = intervals[0][1];
        vector<vector<int>> ret;
        for(size_t i = 1 ; i < n ; ++i)
        {
            int a = intervals[i][0] , b = intervals[i][1];
            if(a <= right)
            {
                //有重叠部分
                right = max(right,b);   
            }
            else 
            {
                //没有重叠
                ret.push_back({left,right});
                left = intervals[i][0] , right = intervals[i][1];
            }
        }
        ret.push_back({left,right});
        return ret;
    }
};

//无重叠区间
class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        sort(intervals.begin(),intervals.end());
        int n = intervals.size();
        int& left = intervals[0][0] , right = intervals[0][1];
        int count = 0;
        for(size_t i = 1 ; i < n ; ++i)
        {
            int a = intervals[i][0] , b = intervals[i][1];
            if(a < right)
            {
                // 重叠了
                count++;
                //合并区间
                right = min(right,b);
            }
            else 
            {
                left = intervals[i][0] , right = intervals[i][1];
            }
        }
        return count;
    }
};